<template>
    <div class="p-2 container">
      <el-form ref="visitorApplyInviteFormRef" :model="form" :rules="rules" label-width="120px" >
        <div>
          <div class="mb20">造访单位信息：</div>
          <div>
            <el-form-item label="申请人：" prop="visitReason">
              {{userStore.nickname}}
            </el-form-item>
            <el-form-item label="来访日期" prop="startTime">
              <div style="width: 360px;">
                <el-date-picker
                  style="width: 360px;"
                  v-model="form.startTime"
                  clearable
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </div>
            </el-form-item>
            <el-form-item label="访客类型：" prop="visitorType">
              <el-input v-model="form.visitorType" placeholder="请输入访客类型" style="width: 360px" />
            </el-form-item>
            <el-form-item label="造访事由：" prop="visitReason">
              <el-input v-model="form.visitReason" placeholder="请输入造访事由" style="width: 360px" />
            </el-form-item>
            <el-form-item label="来访说明：" >
              <el-input v-model="form.remark" type="textarea"  placeholder="请输入造访事由" style="width: 360px" />
            </el-form-item>
          </div>
        </div>

        <div>
          <div class="mb20">访客基本信息：</div>
          <div  style="margin-right: 16px">
            <el-table :data="form.visitorList">
              <el-table-column label="姓名" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.visitorName" clearable style="width: 90px" />
                </template>
              </el-table-column>
              <el-table-column label="性别" align="center" width="100">
                <template #default="scope">
                  <el-select v-model="scope.row.gender" clearable placeholder="请选择访客性别">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="手机号" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.telephone" clearable style="width: 90px" />
                </template>
              </el-table-column>
              <el-table-column label="是否成年" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.visitorDerageFlag" clearable placeholder="请选择访客是否成年" >
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="访客单位" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.visitorDeptName" clearable style="width: 90px" />
                </template>
              </el-table-column>
              <el-table-column label="访客车牌号" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.licensePlateNumber" clearable style="width: 90px" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-tooltip content="删除" placement="top">
                    <el-button link type="primary" icon="Delete" @click="deleteVisitor(scope.$index)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <el-button plain icon="Plus" @click="addVisitor" style="width: 100%; margin-top: 10px">新增</el-button>
          </div>
        </div>

          <div style="margin-top: 50px">
            <div class="mb20">审批信息</div>
            <div>
              <el-form-item label="审批人：" prop="applyUserId">
                <el-select v-model="form.applyUserId" filterable clearable placeholder="请选择审批人" style="width: 360px" >
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div class="dialog-footer" style="float: right;">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </div>
  </template>

  <script setup name="visitorApplyInvite" lang="ts">
  import {
    addvisitorApplyInvite,
    listvisitorApplyInvite,
    updatevisitorApplyInvite
  } from '@/api/access/visitor/visitor-apply-invite';
  import { userInfoVo, visitorApplyInviteForm, visitorApplyInviteQuery, visitorApplyInviteVO } from '@/api/access/visitor/visitor-apply-invite/types';
  import { listUserInfo } from '@/api/access/user/user-info';
  import { visitorAuditForm } from '@/api/access/visitor/visitor-audit/types';
  import { addvisitorAudit } from '@/api/access/visitor/visitor-audit';
  import { listparkBuildingRoom } from '@/api/park/park-building-room';
  import useUserStore from '@/store/modules/user';
  import request from '@/utils/request';
  import { listUser } from '@/api/system/user';
  import { UserVO } from '@/api/system/user/types';
  import { completeTask, getTaskById, startWorkFlow } from '@/api/workflow/task';
  import { StartProcessBo } from '@/api/workflow/workflowCommon/types';

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const userStore = useUserStore();
  const visitorApplyInviteList = ref<visitorApplyInviteVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const areaUserList = ref<userInfoVo[]>([]);
  const userList = ref<UserVO[]>([]);
  const visitorApplyInviteInfo = ref();
  const visitorUserList = ref([]);

  const buildingRoomList = ref([]);

  const queryFormRef = ref<ElFormInstance>();
  const visitorApplyInviteFormRef = ref<ElFormInstance>();

  const submitFormData = ref<StartProcessBo>({
    businessKey: '',
    tableName: '',
    variables: {}
  });
  const taskVariables = ref<Record<string, any>>({});

  const dkMsg = ref(false);

  const dialog = reactive<DialogOption>({
    visible: false,
  });

  const props = defineProps({
  visible: Boolean,
  title: String,
  buttonLoading: Boolean,
  form: Object,
  rules: Object,
  buildingRoomList: Array,
});

const emit = defineEmits(['close', 'submit']);

  const initFormData: visitorApplyInviteForm = {
    visitorApplyInviteId: undefined,
    remark: undefined,
    type: undefined,
    visitReason: undefined,
    inviteUserId: undefined,
    startTime: undefined,
    endTime: undefined,
    visitorType: undefined,
    visitorList: [],
    status: undefined,
    applyUserId: undefined,
    visitorType: undefined,
  };

  const initAuditFormData: visitorAuditForm = {
    visitorApplyInviteId: undefined,
    remark: undefined,
    auditUserId: undefined
  };

  const data = reactive<PageData<visitorApplyInviteForm, visitorApplyInviteQuery>>({
    form: { ...initFormData },
    auditForm: { ...initAuditFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      type: undefined,
      visitReason: undefined,
      inviteUserId: undefined,
      startTime: undefined,
      endTime: undefined,
      params: {}
    },
    rules: {
      visitorApplyInviteId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
      remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
      type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
      visitorType: [{ required: true, message: '访客类型不能为空', trigger: 'blur' }],
      visitReason: [{ required: true, message: '造访事由不能为空', trigger: 'blur' }],
      inviteUserId: [{ required: true, message: '被访问者id不能为空', trigger: 'blur' }],
      startTime: [{ required: true, message: '访问开始时间不能为空', trigger: 'blur' }],
      endTime: [{ required: true, message: '访问结束时间不能为空', trigger: 'blur' }],
    },
    auditRules: {
      auditUserId: [{ required: true, message: '审批人不能为空', trigger: 'blur' }]
    }
  });

  const { queryParams, form, rules, auditForm,auditRules } = toRefs(data);

  /***获取系统用户***/
  const getUserList = async () => {
    loading.value = true;
    const res = await listUser();
    userList.value = res.rows;
    loading.value = false;
  };


  /** 查询访客申请邀约列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listvisitorApplyInvite(queryParams.value);
    visitorApplyInviteList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  };

  /** 获取园区用户列表 */
  const getAreaUserList = async () => {
    // TODO: 获取园区用户列表
    loading.value = true;
    const res = await listUserInfo(queryParams.value);
    areaUserList.value = res.rows;
    loading.value = false;
  };

  /**
   * 获取房间
   */
  const getBuildingRoom = async ()=> {
    const res = await listparkBuildingRoom({type: 4});

    buildingRoomList.value = res.rows

    console.log('获取房间：', res)
  }


  /** 添加访客 */
  const addVisitor = () => {
    form.value.visitorList.push({ name: null });
  };

  /** 删除访客 */
  const deleteVisitor = (index) => {
    form.value.visitorList.splice(index, 1);
  };

  /** 取消按钮 */
  const cancel = () => {
    // reset();
    emit('close')
    // dialog.visible = false;
  };

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    visitorApplyInviteFormRef.value?.resetFields();
  };

  /** 提交按钮 */
  const submitForm = () => {
    if (form.value.startTime !== undefined && form.value.startTime !== null && form.value.startTime.length == 2) {
      const start = form.value.startTime[0];
      const end = form.value.startTime[1];
      form.value.startTime = `${start}`;
      form.value.endTime = `${end}`;
    }
    console.log('提交参数', form.value);

    visitorApplyInviteFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        form.value.inviteUserId = userStore.userId;
        let applyRes = null
        if (form.value.visitorApplyInviteId) {
          applyRes = await updatevisitorApplyInvite(form.value).finally(() => (buttonLoading.value = false));
        } else {
          applyRes = await addvisitorApplyInvite(form.value).finally(() => (buttonLoading.value = false));
        }

        // try {
        //   submitFormData.value.tableName = 'visitor_apply_invite';
        //   submitFormData.value.businessKey = applyRes.data.visitorApplyInviteId;
        //   //流程变量
        //   taskVariables.value = {
        //     entity: applyRes.data,
        //     userList: [1, 3],
        //     userList2: [1, 3]
        //   };
        //   submitFormData.value.variables = taskVariables.value;
        //   const resp = await startWorkFlow(submitFormData.value);
        //
        //   getTaskById(resp.data.taskId).then((response) => {
        //     let taskForm = {taskId: resp.data.taskId, messageType: [1], taskVariables: [], wfCopyList: [] }
        //      completeTask(taskForm);
        //   });
        // } finally {
        //   // buttonLoading.value = false;
        // }
        proxy?.$modal.msgSuccess('操作成功');
        emit('close');
        emit('submit');
        // dialog.visible = false;
        // await getList();
      }
    });
  };


  onMounted(() => {
    getList();
    getAreaUserList();
    getBuildingRoom()
    getUserList();
  });
  </script>
  <style lang="scss" scoped>
  :deep(.el-card__header) {
    height: 60px;
  }
  :deep(.el-card__body) {
    height: calc(100% - 60px);
  }
  :deep(.pagination-container) {
    margin-top: 0;
  }
  .mb20 {
    margin-bottom: 20px;
  }
  .border-box {
    height: 600px;
    padding-top: 20px;

    border: 1px solid #0b0a0a;
    border-radius: 5px;
  }
  .el-input {
    width: 300px;
  }
  p {
      width: 240px;
      padding: 0;
      margin: 0;
    }
      .detail-title {
      margin-bottom: 10px;
      margin-left: 15px;
      border-left: 6px solid #409eff;
      padding-left: 10px;

    }
  </style>
